package com.example.financialsystem.fragment;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.financialsystem.AddRecordActivity;
import com.example.financialsystem.R;
import com.example.financialsystem.datas.AccountBean;
import com.example.financialsystem.datas.OClassificationBean;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import models.Book;
import models.Record;
import models.UserVO;
import okhttp3.Request;
import okhttp3.RequestBody;
import others.ResponseCode;
import others.ServerResponse;
import utils.GsonUtil;
import utils.OkHttpCallback;
import utils.OkhttpUtil;

import static android.content.Context.NOTIFICATION_SERVICE;
import static others.Const.IP;
import static others.Const.JSON;
import static others.Const.PORT;
import static others.Const.SUCCESS;
import static others.Const.currentBook;
import static others.Const.currentUserVo;
import static others.Tools.ToastShow;
import static utils.GsonUtil.Json2Class;

public class OutcomeRecordFragment extends Fragment implements View.OnClickListener {

    private MaterialEditText editNumber;
    private TextView textClass1;
    private TextView textClass2;
    private LinearLayout classLinear;
    private String firstAccount = "现金";
    private TextView textAccount;
    private EditText editRemark;
    private Button buttonSubmit;

    //消费分类滚轮
    private OptionsPickerView OClassificationOptions;
    private ArrayList<OClassificationBean> OClassFirstItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> OClassSecondItems = new ArrayList<>();
    //账户滚轮
    private OptionsPickerView accountOptions;
    private ArrayList<AccountBean> accountFirstItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> accountSecondItems = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_outcome, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        LoadOClassOptionData();
        InitOClassOptionPicker();
        LoadAccountOptionData();
        InitAccountOptionPicker();

        editNumber = (MaterialEditText)getActivity().findViewById(R.id.outcome_number);
        textClass1 = (TextView)getActivity().findViewById(R.id.outcome_class_1);
        textClass2 = (TextView)getActivity().findViewById(R.id.outcome_class_2);
        classLinear = (LinearLayout)getActivity().findViewById(R.id.outcome_class_linear);
        textAccount = (TextView)getActivity().findViewById(R.id.outcome_account);
        editRemark = (EditText) getActivity().findViewById(R.id.outcome_remark);
        buttonSubmit = (Button)getActivity().findViewById(R.id.outcome_submit);
        classLinear.setOnClickListener(this);
        textAccount.setOnClickListener(this);
        buttonSubmit.setOnClickListener(this);
    }

    private void LoadOClassOptionData() {
        /*
         * 注意：如果是添加JavaBean实体数据，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        //选项1
        OClassFirstItems.add(new OClassificationBean(0, "食品酒水", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(1, "居家物业", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(2, "衣服饰品", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(3, "行车交通", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(4, "交流通讯", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(5, "休闲娱乐", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(6, "学习进修", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(7, "人情往来", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(8, "医疗保障", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(9, "金融保险", "描述部分"));

        //选项2
        ArrayList<String> options2Items_00 = new ArrayList<>();
        options2Items_00.add("🥣早午晚餐");
        options2Items_00.add("烟酒茶");
        options2Items_00.add("水果零食");
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("日常用品");
        options2Items_01.add("水电煤气");
        options2Items_01.add("房租");
        options2Items_01.add("物业管理");
        options2Items_01.add("维修保养");
        ArrayList<String> options2Items_02 = new ArrayList<>();
        options2Items_02.add("衣服裤子");
        options2Items_02.add("鞋帽包包");
        options2Items_02.add("化妆饰品");
        ArrayList<String> options2Items_03 = new ArrayList<>();
        options2Items_03.add("公共交通");
        options2Items_03.add("打车租车");
        options2Items_03.add("私家车费用");
        ArrayList<String> options2Items_04 = new ArrayList<>();
        options2Items_04.add("手机费");
        options2Items_04.add("上网费");
        options2Items_04.add("邮寄费");
        ArrayList<String> options2Items_05 = new ArrayList<>();
        options2Items_05.add("运动健身");
        options2Items_05.add("腐败聚会");
        options2Items_05.add("休闲玩乐");
        options2Items_05.add("宠物宝贝");
        options2Items_05.add("旅游度假");
        ArrayList<String> options2Items_06 = new ArrayList<>();
        options2Items_06.add("书报杂志");
        options2Items_06.add("培训进修");
        ArrayList<String> options2Items_07 = new ArrayList<>();
        options2Items_07.add("送礼请客");
        options2Items_07.add("孝敬家长");
        options2Items_07.add("还人钱财");
        options2Items_07.add("慈善捐款");
        ArrayList<String> options2Items_08 = new ArrayList<>();
        options2Items_08.add("药品费");
        options2Items_08.add("保健费");
        options2Items_08.add("美容费");
        options2Items_08.add("治疗费");
        ArrayList<String> options2Items_09 = new ArrayList<>();
        options2Items_09.add("银行手续");
        options2Items_09.add("投资亏损");
        options2Items_09.add("按揭还贷");
        options2Items_09.add("消费税收");
        options2Items_09.add("赔偿罚款");

        OClassSecondItems.add(options2Items_00);
        OClassSecondItems.add(options2Items_01);
        OClassSecondItems.add(options2Items_02);
        OClassSecondItems.add(options2Items_03);
        OClassSecondItems.add(options2Items_04);
        OClassSecondItems.add(options2Items_05);
        OClassSecondItems.add(options2Items_06);
        OClassSecondItems.add(options2Items_07);
        OClassSecondItems.add(options2Items_08);
        OClassSecondItems.add(options2Items_09);
        /*--------数据源添加完毕---------*/
    }

    private void InitOClassOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */

        OClassificationOptions = new OptionsPickerBuilder(getContext(),
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        textClass1.setText(OClassFirstItems.get(options1).getPickerViewText());
                        textClass2.setText(OClassSecondItems.get(options1).get(options2));
                    }
                })
                .setTitleText("分类")
                .setCancelText("添加自定义分类")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //.setLabels("省", "市", "区")
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        textClass1.setText(OClassFirstItems.get(options1).getPickerViewText());
                        textClass2.setText(OClassSecondItems.get(options1).get(options2));
                    }
                })
                .build();

//        pvOptions.setSelectOptions(1,1);
        /*pvOptions.setPicker(options1Items);//一级选择器*/
        OClassificationOptions.setPicker(OClassFirstItems, OClassSecondItems);//二级选择器
        /*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
    }

    private void LoadAccountOptionData() {
        //选项一
        accountFirstItems.add(new AccountBean(0, "现金", null));
        accountFirstItems.add(new AccountBean(1, "信用卡", null));
        accountFirstItems.add(new AccountBean(2, "金融账户", null));
        accountFirstItems.add(new AccountBean(3, "虚拟账户", null));
        accountFirstItems.add(new AccountBean(4, "投资账户", null));

        //选项二
        ArrayList<String> options2Items_00 = new ArrayList<>();
        options2Items_00.add("现金(CNY)");
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("信用卡(CNY)");
        ArrayList<String> options2Items_02 = new ArrayList<>();
        options2Items_02.add("中国银行(CNY)");
        options2Items_02.add("中国建设银行(CNY)");
        options2Items_02.add("中国农业银行(CNY)");
        options2Items_02.add("中国工商银行(CNY)");
        options2Items_02.add("交通银行(CNY)");
        ArrayList<String> options2Items_03 = new ArrayList<>();
        options2Items_03.add("支付宝(CNY)");
        options2Items_03.add("微信钱包(CNY)");
        options2Items_03.add("饭卡(CNY)");
        ArrayList<String> options2Items_04 = new ArrayList<>();
        options2Items_04.add("基金账户(CNY)");
        options2Items_04.add("余额宝(CNY)");
        options2Items_04.add("股票账户(CNY)");

        accountSecondItems.add(options2Items_00);
        accountSecondItems.add(options2Items_01);
        accountSecondItems.add(options2Items_02);
        accountSecondItems.add(options2Items_03);
        accountSecondItems.add(options2Items_04);
        /*数据添加完毕*/
    }

    private void InitAccountOptionPicker() {
        accountOptions = new OptionsPickerBuilder(getContext(),
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        firstAccount = accountFirstItems.get(options1).getPickerViewText();
                        textAccount.setText(accountSecondItems.get(options1).get(options2));
                    }
                })
                .setTitleText("账户")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //.setLabels("省", "市", "区")
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        firstAccount = accountFirstItems.get(options1).getPickerViewText();
                        textAccount.setText(accountSecondItems.get(options1).get(options2));
                    }
                })
                .build();
        accountOptions.setPicker(accountFirstItems, accountSecondItems);//二级选择器
        /*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.outcome_class_linear:
                if (OClassificationOptions!=null) OClassificationOptions.show();
                break;
            case R.id.outcome_account:
                if (accountOptions!=null) {accountOptions.show();}
                break;
            case R.id.outcome_submit:
                String url = "http://" + IP + ":" + PORT + "/portal/record/addRecord.do";
                Record newRecord = ConstructRecord();
                String jsonData = GsonUtil.class2Json(newRecord);
                RequestBody requestBody = RequestBody.create(JSON,jsonData);
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                SendRequest(request);
                break;
        }
    }

    public Record ConstructRecord(){
        String bookId = currentBook.getId();
        String userId = currentUserVo.getId();
        int type = 0;
        int isFamily = currentBook.getType();
        double money = Double.parseDouble(editNumber.getText().toString());
        String firstClass = textClass1.getText().toString();
        String secondClass = textClass2.getText().toString();
        String accountClass = firstAccount;
        String secondAccount = textAccount.getText().toString();
        String remark = editRemark.getText().toString();
        Record newRecord = new Record(null,bookId,userId,type,isFamily,money,
                firstClass,secondClass,
                accountClass,secondAccount,
                remark,null,null,null);
        return newRecord;
    }

    public void SendRequest(Request request){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkhttpUtil.SendRequestWithPost(
                            request,
                            new OkHttpCallback(){
                                @Override
                                public void onFinish(String status, String responseData) {
                                    if (status.equals(SUCCESS)){
                                        Log.d("test", responseData);
                                        ServerResponse<Double> serverResponse = Json2Class(responseData);
                                        if (serverResponse.getStatus() == 0){
                                            Looper.prepare();
                                            ToastShow("添加记录成功");
                                            Looper.loop();
                                        } else if (serverResponse.getStatus()
                                                == ResponseCode.BUDGET_OVERRUN.getCode()){
                                            Looper.prepare();
                                            sendNotification(serverResponse.getData());
                                            ToastShow("预算告急");
                                            Looper.loop();
                                        } else {
                                            Looper.prepare();
                                            ToastShow("添加记录失败，请稍后再试");
                                            Looper.loop();
                                        }
                                    } else {
                                        Looper.prepare();
                                        ToastShow("连接服务器失败,请稍后再试");
                                        Looper.loop();
                                    }
                                }
                            });
                }catch (Exception e){
                    ToastShow("抱歉了亲,我们可能遇到了些麻烦");
                    e.printStackTrace();
                }
            }
        }).run();
    }

    public void sendNotification(double cost){
        String id = "my_channel_01";
        String name="我是渠道名字";
        NotificationManager notificationManager;
        notificationManager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE);
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(getContext())
                    .setChannelId(id)
                    .setContentTitle("预算预警提示")
                    .setContentText("账本预算为"+currentBook.getBudget()+"元，您已经消费了"+cost+"元了")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                    .setWhen(System.currentTimeMillis())
                    .build();
        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext())
                    .setContentTitle("预算预警提示")
                    .setContentText("账本预算为"+currentBook.getBudget()+"元，您已经消费了"+cost+"元了")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .setOngoing(true);
            notification = notificationBuilder.build();
        }
        notificationManager.notify(111123, notification);
    }

}
